using Gateway.Common.Cache;
using Gateway.Infrastructure.Provider.Operator;
using Gateway.IQuery.Menu;
using Gateway.IQuery.Sign;
using Aurora.Redis;

namespace Gateway.Query;

/// <summary>
/// 
/// </summary>
public class AuthService : IAuthService
{
    private readonly IMenuQuery _menuQuery;
    private readonly IOperatorProvider _operatorProvider;
    private readonly IRedisCache _redisCache;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="menuQuery"></param>
    /// <param name="operatorProvider"></param>
    /// <param name="redisCache"></param>
    public AuthService(IMenuQuery menuQuery, IOperatorProvider operatorProvider, IRedisCache redisCache)
    {
        _menuQuery = menuQuery;
        _operatorProvider = operatorProvider;
        _redisCache = redisCache;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="roleIds"></param>
    /// <returns></returns>
    public async Task<List<string>> ResetApisWithOwner(string userId = default, List<string> roleIds = default)
    {
        if (string.IsNullOrEmpty(userId))
        {
            userId = _operatorProvider.GetOperator().OperatorId;
        }

        if (roleIds == null || roleIds.Count < 1)
        {
            roleIds = _operatorProvider.GetOperator().RoleIdList;
        }
        var apis = await _menuQuery.GetMenuApis(roleIds);
        var apiList = apis.Select(p => p.Url).ToList();
        CacheApisWithOwner(apiList,userId);
        return apiList;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public async Task<List<string>> ResetPermissionWithOwner()
    {
        var permissions = await _menuQuery.GetFuncPermissionByRoleIds(_operatorProvider.GetOperator().RoleIdList);
        CachePermissionWithOwner(permissions, _operatorProvider.GetOperator().OperatorId);
        return permissions;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="data"></param>
    /// <param name="userId"></param>
    /// <returns></returns>
    public bool CachePermissionWithOwner(List<string> data, string userId)
    {
        _redisCache.Add(CacheKeys.UserPermissions + userId, data,
            TimeSpan.FromHours(12));
        return true;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="data"></param>
    /// <param name="userId"></param>
    /// <returns></returns>
    public bool CacheApisWithOwner(List<string> data, string userId)
    {
        _redisCache.Add(CacheKeys.UserCacheApi + userId, data,
            TimeSpan.FromHours(12));
        return true;
    }
}